package com.config;

import org.apache.catalina.core.ApplicationFilterChain;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContainerInitializer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

@Configuration
public class FilterConfig {

    @Bean
    public Filter characterEncodingFilter(){
        return new CharacterEncodingFilter(StandardCharsets.UTF_8.name(),true,true);
    }

    /**
     * 请求从 tomcat -> filter chain -> servlet -> controller 的过程
     * Tomcat 对 {@link FilterChain} 的一个实现
     * @see ApplicationFilterChain#internalDoFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     * 优先执行所有的过滤器，过滤器执行完成之后再调用 DispatcherServlet
     * @return
     */
    @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean(){
        Filter filter = characterEncodingFilter();
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(filter);

        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}
